package com.xopencode.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Mcb
 * @date 2022/5/25
 * @apiNote lock版本生产者和消费者
 */
public class LockDemo {

    public static final Data2 data = new Data2();

    public static void main(String[] args) {
        new Thread(() -> {
            data.increment();
        }, "A").start();

        new Thread(() -> {
            data.increment();
        }, "B").start();

        new Thread(() -> {
            data.decrement();
        }, "C").start();

        new Thread(() -> {
            data.decrement();
        }, "D").start();
    }
}

class Data2 {
    private int number = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() {
        //加锁
        lock.lock();
        try {
            while (number != 0) {
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            //通知其他线程
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        //加锁
        lock.lock();
        try {
            while (number == 0) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            //通知其他线程
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
